﻿using Commons;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Messaging;
using System.Threading;
using System.Web;

namespace CamScanWebService
{
    /// <summary>
    /// upload 的摘要说明
    /// </summary>
    public class upload : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/html";
            HttpFileCollection files = context.Request.Files;
            HttpPostedFile postedFile = files["file"];
            string fileName = System.IO.Path.GetFileName(postedFile.FileName);
            fileName = Guid.NewGuid() + System.IO.Path.GetExtension(fileName).ToLower();
            string SaveFilePath = ConfigurationManager.AppSettings["InputPath"] + fileName;
            postedFile.SaveAs(SaveFilePath);

            SendMessage(fileName);
            string OutFilePath = ConfigurationManager.AppSettings["OutputPath"] + fileName;
            while (!File.Exists(OutFilePath))
            {
                Thread.Sleep(500);
            }
           
            string html;
            using(StreamReader reader= new StreamReader(context.Server.MapPath("/output.html")))
            {
               
                html = reader.ReadToEnd().Replace("@path", "output/" + fileName);
               
            }

            context.Response.Write(html);
            context.Response.End();
        }
        private void SendMessage(string path)
        {
            try
            {
                Result result = new Result();
                result.Path = path;
                System.Messaging.Message msg1 = new System.Messaging.Message();
                msg1.Body = result;
                MessageQueue msgQ1 = new MessageQueue(ConfigurationManager.AppSettings["QueuePath"]);
                msgQ1.Send(msg1);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error creating the message \n" + ex.Message);
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}